#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>

#define NUM 10000

//设置票数
int tickets = NUM;
//创建互斥锁
pthread_mutex_t lock;

void* ticket(void* argv)
{
  //得到线程编号
  int id = (long)argv;
  
  while(true){
    //加锁
    pthread_mutex_lock(&lock);
    if(tickets > 0){
      printf("thread[%d] tickets:%d\n", id, tickets--);
      //解锁
      pthread_mutex_unlock(&lock);
      //解锁后休眠1微秒，给其他线程抢夺互斥锁的机会
      usleep(1);
    }    
    else{
      pthread_mutex_unlock(&lock);
      break;
    }
  }
}

int main()
{
  //初始化互斥锁
  pthread_mutex_init(&lock, nullptr);

  //创建线程
  pthread_t thds[5];
  for(long i = 0; i < 5; i++){
    pthread_create(&thds[i], nullptr, ticket, (void*)i);
  }

  //等待线程
  for(int i = 0; i < 5; i++){
    pthread_join(thds[i], nullptr);
  }

  //pthread_t thd1, thd2, thd3, thd4; 
  //pthread_create(&thd1, nullptr, ticket, (void*)1);
  //pthread_create(&thd2, nullptr, ticket, (void*)2);
  //pthread_create(&thd3, nullptr, ticket, (void*)3);
  //pthread_create(&thd4, nullptr, ticket, (void*)4);

  //pthread_join(thd1, nullptr);
  //pthread_join(thd2, nullptr);
  //pthread_join(thd3, nullptr);
  //pthread_join(thd4, nullptr);
  
  //销毁互斥锁
  pthread_mutex_destroy(&lock);

  return 0;
}
